package org.atlantis.sbe.actor

import scala.actors.Actor
import scala.actors.Actor._

abstract class PingMessage
case object Start extends PingMessage
case object SendPing extends PingMessage
case object Pong extends PingMessage

abstract class PongMessage
case object Ping extends PongMessage
case object Stop extends PongMessage

class Ping(count: Int, pong: Actor) extends Actor {

    override def act() {
        println("Ping: Initializing with count" + count + ": " + pong)
        var pingsLeft = count
        loop {
            react {
                case Start =>
                    println("Ping: starting.")
                    pong ! Ping
                    pingsLeft = pingsLeft - 1
                case SendPing =>
                    pong ! Ping
                    pingsLeft = pingsLeft - 1
                case Pong =>
                    if (pingsLeft % 100000 == 0)
                        println("Ping: pong from: " + sender)
                    if (pingsLeft > 0) {
                        self ! SendPing
                    } else {
                        println("Ping: Stop.")
                        pong ! Stop
                        exit("stop")
                    }
            }
        }
    }
}

class Pong extends Actor {
    override def act() {
        var pongCount = 0
        loop {
            react {
                case Ping =>
                    if (pongCount % 100000 == 0)
                        println("Pong: ping " + pongCount + " from: " + sender)
                    sender ! Pong
                    pongCount = pongCount + 1
                case Stop =>
                    println("Pong: Stop.")
                    exit("stop")
            }
        }
    }
}

object pingpong extends App {
    val pong = new Pong
    val ping = new Ping(1000000, pong)
    ping.start
    pong.start
    ping ! Start
}